package com.fzy.core.converters;

import java.lang.reflect.Member;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import ognl.DefaultTypeConverter;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.util.XWorkConverter;

public class MyDateConverter extends DefaultTypeConverter {

	private static final SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd");
	
	public Object convertValue(Map context, Object target, Member member, String property, Object value, Class toClass) {
		Object result = null;
		if (toClass == Date.class) {
			result = doConvertToDate(context, target, property, value);
		} else if (toClass == String.class) {
			result = doConvertToString(value);
		}
		return result;
	}

	private Date doConvertToDate(Map context, Object target, String property, Object value) {
		Date result = null;

		if (value instanceof String) {
			try {
				result = sdf.parse((String) value);
			} catch (java.text.ParseException e) {
				handleConversionException(context, property, value, target);
			}

		} else if (value instanceof Object[]) {
			Object[] array = (Object[]) value;
			if ((array != null) && (array.length >= 1)) {
				value = array[0];
				result = doConvertToDate(context, target, property, value);
			}
		} else if (Date.class.isAssignableFrom(value.getClass())) {
			result = (Date) value;
		}
		return result;
	}
	
    protected void handleConversionException(Map context, String property, Object value, Object object) {
        if ((Boolean.TRUE.equals(context.get(XWorkConverter.REPORT_CONVERSION_ERRORS)))) {

            String realProperty = property;
            String fullName = (String) context.get(XWorkConverter.CONVERSION_PROPERTY_FULLNAME);

            if (fullName != null) {
                realProperty = fullName;
            }

            Map conversionErrors = (Map) context.get(ActionContext.CONVERSION_ERRORS);

            if (conversionErrors == null) {
                conversionErrors = new HashMap();
                context.put(ActionContext.CONVERSION_ERRORS, conversionErrors);
            }

            conversionErrors.put(realProperty, value);
        }
    }

	private String doConvertToString(Object value) {
		String result = null;
		if (value instanceof Date) {
			result = sdf.format(value);
		}
		return result;
	}
}
